package com.droid.library.widget.edittext;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;

import com.xinye.lib.R;

/**
 * 限制输入浮点数类型的EditText
 *
 * @author wangheng
 */
public class NumberDecimalEditText extends BaseEditText implements TextWatcher {

    private int decimalDigit = 2;

    public NumberDecimalEditText(Context context) {
        super(context);

        init(context,null);
    }

    public NumberDecimalEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs);
    }

    public NumberDecimalEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        if(attrs != null){
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.NumberDecimalEditText);
            decimalDigit = ta.getInt(R.styleable.NumberDecimalEditText_decimalDigit,decimalDigit);
            ta.recycle();
        }
    }

    public void setDecimalDigit(int decimalDigit) {
        this.decimalDigit = decimalDigit;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        addTextChangedListener(NumberDecimalEditText.this);
    }

    @Override
    protected void onDetachedFromWindow() {
        removeTextChangedListener(NumberDecimalEditText.this);
        super.onDetachedFromWindow();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String temp = s.toString();
        int posDot = temp.indexOf(".");
        if (posDot <= 0) {
            return;
        }
        if (temp.length() - posDot - 1 > decimalDigit) {
            s.delete(posDot + decimalDigit, temp.length());
        }
    }
}
